<?php


class UserIdentity extends CUserIdentity
{
    protected $_id;

    public function __construct($userName=false,$password=false)
    {
        if($userName) $this->username=$userName;
        if($password) $this->password=$password;
    }

    public function rules()
    {
        return array(
            array('username', 'required', 'message'=>'Укажите свой логин или электронный аадрес'),
            array('password', 'required', 'message'=>''),
        );
    }

    public function authenticate()
    {
        $model=$this->getUserModel();

        if($model===null || $model->password!==$model->getPasswordHash($this->password)){
            $this->errorCode='Не найдено такого соответсвия логина (e-mail адреса) и пароля.';
        }else{
            $this->login($model);
        }

        return !$this->errorCode;
    }

    public function SNLogin()
    {
        if($service=$code=Yii::app()->request->getQuery('service')) Yii::app()->session['SNServiceName']=$service;
        elseif($service=Yii::app()->session['SNServiceName']) unset(Yii::app()->session['SNServiceName']);
        $service=Yii::app()->snauth->getService($service);

        if($service && $service->isAuthenticated() && $userInfo=$service->getUserInfo()){
            $this->username=$userInfo['user']['userName'];

            if(!$user=$this->getUserModel($this->username)){
                $user=new User();
                $profile=new Profile();
                $user->attributes=$userInfo['user'];
                $profile->attributes=$userInfo['profile'];

                $transaction=Yii::app()->db->beginTransaction();

                try{
                    if(!$user->password){
                        $user->password=$user->getRandomString();
                        $user->sendPassword($user->password);
                    }
                    $user->save(false);
                    $profile->userId=$user->id;
                    $profile->save(false);
                    $transaction->commit();
                }catch(Exception $e){
                    $transaction->rollback();
                    Yii::app()->user->setFlash('userMessage','Неудачная попытка! Попробуйте ещё раз.'.'<br />'.$e);
                }
            }

            return $this->login($user);
        }
        return false;
    }

    public function getId()
    {
        return $this->_id;
    }

    protected function getUserModel()
    {
        strpos($this->username,'@') ? $model=User::model()->findByAttributes(array('email'=>$this->username)) : $model=User::model()->findByAttributes(array('userName'=>$this->username));
        return $model;
    }

    protected function login($userModel)
    {
        $this->_id=$userModel->id;
        $this->setState('name', $userModel->profile->firstName);
        if(Yii::app()->user->login($this)){
            $this->errorCode=self::ERROR_NONE;
            return true;
        }
        return false;
    }
}